export default{
	namespaced: true,
	
	// 购物车的数组，用来存储购物车中每个商品的信息对象
	// 每个商品的信息对象，都包含以下6个属性
	// {goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state}
	state: () => ({
		cart:  JSON.parse(uni.getStorageSync('cart') ||'[]')
	}),
	
	mutations: {
		addToCart(state, goods) {
			const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
			if (!findResult) {
				state.cart.push(goods)
			} else {
				findResult.goods_count++
			}
			
			this.commit('my-cart/saveToStorage')
			
		},
		saveToStorage(state) {
			uni.setStorageSync('cart', JSON.stringify(state.cart))
		},
		
		updateState(state, goods) {
			let findResult = state.cart.find(x => x.goods_id === goods.goods_id)
			
			if (findResult) {
				findResult.goods_state = goods.goods_state
				
				this.commit('my-cart/saveToStorage')
			}
		},
		updateGoodsCount(state, goods) {
			const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
			if (findResult) {
				findResult.goods_count = goods.goods_count
				
				this.commit('my-cart/saveToStorage')
			}
		},
		removeGoods(state, goods_id) {
			state.cart = state.cart.filter(item => item.goods_id !== goods_id)
			this.commit('my-cart/saveToStorage')
		},
		
		// // 全选
		// checkAll(state) {
		// 	state.cart.map(item => item.goods_state = true)
		// 	this.commit('my-cart/saveToStorage')
		// },
		// // 全不选
		// clearAll(state) {
		// 	state.cart.map(item => item.goods_state = false)
		// 	this.commit('my-cart/saveToStorage')
		// }
		
		// 更改购物车商品的状态 全选/全不选
		updateGoodsState(state, isState) {
			state.cart.forEach(item => item.goods_state = isState)
			this.commit('my-cart/saveToStorage')
		}
		
	},
	
	getters: {
		// 总数量
		total(state) {
			// let c = 0
			// state.cart.forEach(item => c += item.goods_count)
			// return c
			return state.cart.reduce((total, item) => total + item.goods_count, 0)
		},
		// 选择的商品数量
		fullCheck(state) {
			return state.cart.filter(x => x.goods_state).reduce((total, item) => total + item.goods_count, 0)
		},
		
		// 选择的商品总价
		prices(state) {
			return state.cart.filter(x => x.goods_state).reduce((total, item) => total += (item.goods_count * item.goods_price), 0)
		}
	}
}